<template>
  <div>
    <div class="upload-img" v-if="imgUrlList.length > 0">
      <div
        class="img-item"
        v-for="(item, index) in imgUrlList"
        :key="item"
        style="margin-top: -6px"
      >
        <img :src="item" />
        <i
          class="el-icon-close"
          @click="handleRemove(index)"
          v-if="!isDisabled && rules.showClose"
        ></i>
      </div>
    </div>
    <el-upload
      :multiple="rules.multiple"
      class="avatar-uploader"
      action
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      style="display: inline-block ; border:1px solid #eee"
      list-type="picture"
      v-if="!isDisabled"
    >
      <!-- v-if="imgUrlList.length < rules.maxLen" -->
      <i class="el-icon-plus avatar-uploader-icon avatar"></i>
    </el-upload>
  </div>
</template>

<script>
import { uploadFile } from "@/api/article/group";

export default {
  name: "UploadMultiple",
  /**
   * imgUrlList: 图片地址list
   * maxLen: 最多可上传几张
   * showClose：控制删除按钮的展示
   */
  props: {
    uploadList: {
      type: [Array, String],
      default: function () {
        return [];
      },
    },
    uploadRule: {
      type: Object,
      default: function () {
        return {};
      },
    },
    isDisabled:{
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      rules: {},
      imgUrlList: [], // 要拼接前缀
      parentList: [], // 给父组件传
    };
  },

  watch: {
    // uploadList(newVal) {
    //   if (newVal) {
    //     this.init();
    //     unwatch();
    //   }
    // },
  },
  mounted() {
    this.init();
    const unwatch = this.$watch("uploadList", function (newValue, oldValue) {
      // console.log("newValue", newValue);
      this.init();
      unwatch();
    });
  },

  methods: {
    init() {
      this.rules.maxLen = this.uploadRule.maxLen || 2;
      this.rules.sizeLen = this.uploadRule.sizeLen || 2;
      this.rules.type = this.uploadRule.type || ["jpg", "png", "gif", "jpeg"];
      this.rules.showClose = this.uploadRule.showClose || true;
      this.rules.multiple = this.uploadRule.multiple || false;
      // const url = window.globalConfig.IMAGE_API;
      console.log("this.uploadList", this.uploadList);
      if (typeof this.uploadList === "object" && this.uploadList.length > 0) {
        this.uploadList.forEach((item) => {
          this.imgUrlList.push(window.globalConfig.IMAGE_API + item);
          this.parentList.push(item);
          this.imgUrlList = Array.from(new Set(this.imgUrlList));
          this.parentList = Array.from(new Set(this.parentList));
          console.log("set", this.imgUrlList);
        });
      } else if (typeof this.uploadList === "string" && this.uploadList) {
        this.imgUrlList = [];
        this.imgUrlList.push(
          window.globalConfig.IMAGE_API + this.uploadList
        );
      }
      console.log("this.imgUrlList", this.imgUrlList);
    },

    // 首图---上传成功之前
    beforeAvatarUpload(file) {
      const isJPG = this.rules.type.includes(file.name.split(".")[1]);
      const isLt2M = file.size / 1024 / 1024 < this.rules.sizeLen;
      let msg = "上传图片支持";
      if (this.imgUrlList.length >= this.rules.maxLen) {
        return this.$message.error(`最多可上传${this.rules.maxLen}张图片!`);
      }
      console.log("isJPG", file);
      if (!isJPG) {
        this.rules.type.forEach((item) => {
          msg += item;
        });
        this.$message.error(msg + "格式!");
      } else if (!isLt2M) {
        this.$message.error(
          "上传图片大小不能超过" + this.uploadRule.sizeLen + "M!"
        );
      } else {
        const formData = new FormData();
        formData.append("file", file);
        uploadFile(formData).then(
          (res) => {
            if (res.code === 200) {
              const url =
                window.globalConfig.IMAGE_API + res.data.url;
              this.imgUrlList.push(url);
              // 将多余得删除
              if (this.imgUrlList.length > this.rules.maxLen) {
                this.imgUrlList.pop();
              }
              if (!this.rules.multiple) {
                this.$emit("update:uploadList", res.data.url);
              } else {
                this.parentList.push(res.data.url);
                this.$emit("update:uploadList", this.parentList);
              }
            }
          },
          (err) => {
            this.$message.error("上传失败！");
          }
        );
        return false;
      }
      return isJPG && isLt2M;
      // const formData = new FormData();
      // formData.append("file", file);
      // uploadFile(formData).then((res) => {
      //   if (res.code === 200) {
      //     const url = window.globalConfig.IMAGE_API + res.data.url;
      //     this.imgUrlList.push(url);
      //   }
      // });
      // return false;
    },
    // 删除上传图片
    handleRemove(index) {
      this.imgUrlList.splice(index, 1);
      this.parentList.splice(index, 1);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";
</style>
